import md5 from './md5.js'
// 校验参数
function createSigin() {
	let appid = 'c8d46d341bea4fd5bff866a65ff8aea9'
	let key = 'da5ce0c628b722cfa5791dab836c158ea4694d7188b3b971b1778375'
	let timeout = parseInt(new Date().getTime() / 1000)
	return {
		'appId': appid,
		'key': key,
		'timeOut': timeout
	}
}

function signStringify(obj) {
	var arr = [];
	var params = '';

	for (var item in obj) {
		// 将所有非空参数(不为null,不为"",不为"   ")
		if (typeof obj[item] !== 'object') {
			if (obj[item] !== null && !/^\s*$/.test(obj[item]) && obj[item] != '' && obj[item] != '0') {
				if (typeof obj[item] === 'boolean') {
					params = item.toLowerCase() + '=' + (obj[item] ? 'true' : 'false');
				} else {
					params = item.toLowerCase() + '=' + obj[item];
				}
				arr.push(params);
			}
		}
	}
	arr.sort();
	return arr;
}
const request = (config) => {
	let Sign = ''
	let num = 0
	let obj = {
		'appid': createSigin().appId,
		'key': createSigin().key,
		'nowtime': createSigin().timeOut,
		'token': uni.getStorageSync('utoken')
	}
	// 处理 apiUrl
	config.url = 'http://zuqiu2.boxs.art/mobile' + config.url
	// config.url = 'http://cw.ssjt.group//mobile' + config.url;
	if (!config.data) {
		config.data = {};
	} else {
		for (let i in config.data) {
			if (typeof config.data[i] == 'object') {
				continue;
			} else {
				obj[i] = config.data[i]
			}
		}
	}
	obj = signStringify(obj)
	console.log(obj)
	for (let i in obj) {
		num++
		if (num < Object.getOwnPropertyNames(obj).length - 1) {
			Sign += `${obj[i]}` + 'GAME&CMS'
		} else {
			Sign += `${obj[i]}`
		}
	}
	config.header.sign = md5(Sign).toUpperCase()
	config.header.nowtime = createSigin().timeOut
	config.header.appid = createSigin().appId

	let promise = new Promise(function(resolve, reject) {
		uni.request(config).then(responses => {
			// 异常
			if (responses[0]) {
				reject({
					message: "网络超时"
				});
			} else {
				let response = responses[1]
					.data; // 如果返回的结果是data.data的，嫌麻烦可以用这个，return res,这样只返回一个data
				resolve(response);
			}
		}).catch(error => {
			reject(error);
		})
	})
	return promise;
};



export default request;